//
//  LGCareMonitorEditView.m
//  HeartDiseaseManage
//
//  Created by Bovin on 2024/8/4.
//

#import "LGCareMonitorEditView.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
@interface LGCareMonitorEditView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,LGCareMonitorInputDelegate>
/**   */
@property (nonatomic , strong)UICollectionView *collectionView;
/**  测量频率 */
@property (nonatomic , strong)NSArray *rateArray;
@property (nonatomic , copy)NSString *rateType;
@property (nonatomic , copy)NSString *rateNumber;
@property (nonatomic , strong)NSIndexPath *indexPath;
@property (nonatomic , strong)NSMutableDictionary *inputDic;


/**  测量时间 */
@property (nonatomic , strong)NSArray *timeArray;
@property (nonatomic , strong)NSMutableArray *selectTimes;

@end

@implementation LGCareMonitorEditView
-(instancetype)initWithTitle:(NSString *)title bottomBtn:(NSArray *)btnArray baseHeight:(CGFloat)baseHeight{
    self = [super initWithTitle:title bottomBtn:btnArray baseHeight:baseHeight];
    if (self) {
        [IQKeyboardManager sharedManager].enable = YES;
        [self.baseView addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.baseView).offset(viewPix(40));
            make.left.equalTo(self.baseView).offset(viewPix(16));
            make.right.equalTo(self.baseView).offset(-viewPix(16));
            make.bottom.equalTo(self.buttonView.mas_top);
        }];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    self.rateArray = dataDic[@"frequencySelect"];
    self.timeArray = dataDic[@"timeSelect"];
    self.rateType = LGNSString(dataDic[@"frequency"][@"type"]);
    self.rateNumber = LGNSString(dataDic[@"frequency"][@"nums"]);
    self.selectTimes = [NSMutableArray arrayWithArray:dataDic[@"times"]];
    [self.inputDic setValue:self.rateNumber forKey:self.rateType];
    [self.collectionView reloadData];
}

-(void)bottomButtonTouchedWithIndex:(NSInteger)index{
    [super bottomButtonTouchedWithIndex:index];
    if (index == 2) {
        if (([self.rateType isEqualToString:@"1week"] || [self.rateType isEqualToString:@"1month"])&&self.rateNumber.length == 0) {
            [TooltipView showMessage:@"请输入天数" offset:0];
            return;
        }
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:self.dataDic];
        [tempDic setValue:@{@"type":self.rateType,@"nums":self.rateNumber} forKey:@"frequency"];
        [tempDic setValue:self.selectTimes forKey:@"times"];
        if (self.editFinishAction) {
            self.editFinishAction(tempDic);
        }
    }
    [self hiddenViewAnmation];
}

-(void)inputValueChanged:(NSString *)content type:(NSString *)type{
    [self.inputDic setValue:content forKey:type];
    self.rateNumber = content;
}

-(void)keyboardWillShow:(NSNotification *)notification{
    NSInteger duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] integerValue];
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat height = keyboardFrame.size.height;
    height = self.rateArray.count*viewPix(48)+viewPix(90)+height;
    [UIView animateWithDuration:duration animations:^{
        self.baseView.frame = CGRectMake(0, Screen_H-height, Screen_W, self.baseView.bounds.size.height);
    }];
}

-(void)keyboardWillHide:(NSNotification *)notification{
    NSInteger duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] integerValue];
    [UIView animateWithDuration:duration animations:^{
        self.baseView.frame = CGRectMake(0, Screen_H-self.baseView.bounds.size.height+viewPix(20), Screen_W, self.baseView.bounds.size.height);
    } completion:^(BOOL finished) {
       
    }];
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return (section == 0)?self.rateArray.count:self.timeArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        NSString *value = LGNSString(self.rateArray[indexPath.item][@"value"]);
        if([value isEqualToString:@"1week"] || [value isEqualToString:@"1month"]){
            LGCareMonitorInputItem *inputItem = [collectionView dequeueReusableCellWithReuseIdentifier:@"inputItem" forIndexPath:indexPath];
            inputItem.dataDic = self.rateArray[indexPath.item];
            inputItem.isSelected = [self.rateType isEqualToString:value]?YES:NO;
            inputItem.textField.text = [self.inputDic.allKeys containsObject:value]?LGNSString(self.inputDic[value]):@"";
            inputItem.delegate = self;
            return inputItem;
        }else{
            LGCareMonitorSelectItem *selectItem = [collectionView dequeueReusableCellWithReuseIdentifier:@"selectItem" forIndexPath:indexPath];
            selectItem.dataDic = self.rateArray[indexPath.item];
            selectItem.isSelected = [self.rateType isEqualToString:value]?YES:NO;
            return selectItem;
        }
    }else{
        NSString *value = LGNSString(self.timeArray[indexPath.item][@"value"]);
        LGCareMonitorSelectItem *selectItem = [collectionView dequeueReusableCellWithReuseIdentifier:@"selectItem" forIndexPath:indexPath];
        selectItem.dataDic = self.timeArray[indexPath.item];
        selectItem.isSelected = [self.selectTimes containsObject:value]?YES:NO;
        return selectItem;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        NSString *value = LGNSString(self.rateArray[indexPath.item][@"value"]);
        self.rateType = value;
        self.rateNumber = @"";
        self.indexPath = indexPath;
        [self.collectionView reloadData];
        if([value isEqualToString:@"1week"] || [value isEqualToString:@"1month"]){
            [self performSelector:@selector(textFieldBeginEditing) withObject:nil afterDelay:0.2];
        }
    }else{
        NSString *value = LGNSString(self.timeArray[indexPath.item][@"value"]);
        if([self.selectTimes containsObject:value]){
            [self.selectTimes removeObject:value];
        }else{
            if([value isEqualToString:@"T"]){
                [self.selectTimes removeAllObjects];
            }else if ([self.selectTimes containsObject:@"T"]){
                [self.selectTimes removeObject:@"T"];
            }
            [self.selectTimes addObject:value];
        }
        [self.collectionView reloadData];
    }
}

-(void)textFieldBeginEditing{
    LGCareMonitorInputItem *item = (LGCareMonitorInputItem *)[self.collectionView cellForItemAtIndexPath:self.indexPath];
    [item.textField becomeFirstResponder];
    self.rateNumber = (item.textField.text.length>0)?item.textField.text:@"";
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return CGSizeMake(Screen_W-viewPix(32), viewPix(40));
    }else{
        return CGSizeMake((Screen_W-viewPix(32)-viewPix(16))/3.0, viewPix(40));
    }
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    LGCareMonitorHeaderView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    headView.titleLabel.text = (indexPath.section == 0)?@"测量频率":@"测量时间(可多选)";
    return headView;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(Screen_W-viewPix(32), viewPix(50));
}

-(UICollectionView *)collectionView{
    if(!_collectionView){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumInteritemSpacing = viewPix(8);
        layout.minimumLineSpacing = viewPix(8);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(viewPix(16), viewPix(40), Screen_W-viewPix(32), viewPix(365)) collectionViewLayout:layout];
        [_collectionView registerClass:[LGCareMonitorHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        [_collectionView registerClass:[LGCareMonitorSelectItem class] forCellWithReuseIdentifier:@"selectItem"];
        [_collectionView registerClass:[LGCareMonitorInputItem class] forCellWithReuseIdentifier:@"inputItem"];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.scrollEnabled = YES;
        _collectionView.dataSource = self;
        _collectionView .delegate = self;
    }
    return _collectionView;
}

-(NSMutableDictionary *)inputDic{
    if(!_inputDic){
        _inputDic = [NSMutableDictionary dictionary];
    }
    return _inputDic;
}

-(NSMutableArray *)selectTimes{
    if(!_selectTimes){
        _selectTimes = [NSMutableArray array];
    }
    return _selectTimes;
}

@end




#pragma mark
#pragma mark ====> LGCareMonitorSelectItem

@interface LGCareMonitorSelectItem()
/**   */
@property (nonatomic , strong)UIButton *contentBtn;

@end


@implementation LGCareMonitorSelectItem

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.contentBtn];
        [self.contentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self.contentView);
            make.left.equalTo(self.contentView).offset(1);
            make.right.equalTo(self.contentView).offset(-1);
        }];
    }
    return self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    [self.contentBtn setTitle:LGNSString(dataDic[@"title"]) forState:UIControlStateNormal];
}

-(void)setIsSelected:(BOOL)isSelected{
    _isSelected = isSelected;
    self.contentBtn.selected = isSelected;
    NSString *borderColor = (isSelected == YES)?@"#5E8EF5":@"#EEEEEE";
    self.contentBtn.layer.borderColor = [UIColor colorWithString:borderColor].CGColor;
}

-(UIButton *)contentBtn{
    if(!_contentBtn){
        _contentBtn = [UIButton buttonWithTitle:@"" titleFont:LGFontWeight(14, UIFontWeightMedium) normalColor:@"#606266" selectColor:@"#5E8EF5"];
        [_contentBtn setBackgroundColor:@"#FFFFFF" selectColor:@"#E5F1FF"];
        _contentBtn.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(10), 0, viewPix(10));
        [_contentBtn addBorder:@"#EEEEEE" lineWidth:1 cornerRidus:3];
        _contentBtn.titleLabel.numberOfLines = 2;
        _contentBtn.userInteractionEnabled = NO;
        _contentBtn.cornerRidus = 3;
    }
    return _contentBtn;
}

@end



#pragma mark
#pragma mark ====> LGCareMonitorInputItem

@interface LGCareMonitorInputItem()<UITextFieldDelegate>
/**   */
@property (nonatomic , strong)UIButton *contentBtn;
/**   */
@property (nonatomic , strong)UILabel *leftLabel;
/**   */
@property (nonatomic , strong)UILabel *rightLabel;
/**   */
@property (nonatomic , strong)UIView *lineView;

@end

@implementation LGCareMonitorInputItem

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubView];
    }
    return self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    self.leftLabel.text = LGNSString(dataDic[@"title"]);
}

-(void)setIsSelected:(BOOL)isSelected{
    _isSelected = isSelected;
    self.contentBtn.selected = isSelected;
    NSString *borderColor = (isSelected == YES)?@"#5E8EF5":@"#EEEEEE";
    self.contentBtn.layer.borderColor = [UIColor colorWithString:borderColor].CGColor;
    NSString *textColor = (isSelected == YES)?@"#5E8EF5":@"#606266";
    self.lineView.backgroundColor = [UIColor colorWithString:textColor];
    self.leftLabel.textColor = [UIColor colorWithString:textColor];
    self.rightLabel.textColor = [UIColor colorWithString:textColor];
    self.textField.textColor = [UIColor colorWithString:textColor];
}

-(void)textFieldEditingChanged:(UITextField *)textField{
    NSString *content = textField.text.length>0?textField.text:@"";
    if(self.delegate && [self.delegate respondsToSelector:@selector(inputValueChanged:type:)]){
        [self.delegate inputValueChanged:content type:LGNSString(self.dataDic[@"value"])];
    }
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return YES;
}

-(void)createSubView{
    [self.contentView addSubview:self.contentBtn];
    [self.contentBtn addSubview:self.leftLabel];
    [self.contentBtn addSubview:self.textField];
    [self.contentBtn addSubview:self.rightLabel];
    [self.contentBtn addSubview:self.lineView];
    [self.contentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(1);
        make.right.equalTo(self.contentView).offset(-1);
    }];
    [self.leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.textField.mas_left);
        make.centerY.equalTo(self.contentBtn);
    }];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.contentBtn);
        make.bottom.equalTo(self.contentBtn).offset(-viewPix(5));
        make.width.equalTo(@(viewPix(50)));
        make.height.equalTo(@(viewPix(35)));
    }];
    [self.rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.textField.mas_right);
        make.centerY.equalTo(self.contentBtn);
    }];
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.textField).offset(-viewPix(2));
        make.left.right.equalTo(self.textField);
        make.height.equalTo(@(1.0));
    }];
}

-(UIButton *)contentBtn{
    if(!_contentBtn){
        _contentBtn = [UIButton buttonWithTitle:@"" titleFont:LGFontWeight(14, UIFontWeightMedium) normalColor:@"#606266" selectColor:@"#5E8EF5"];
        [_contentBtn setBackgroundColor:@"#FFFFFF" selectColor:@"#E5F1FF"];
        _contentBtn.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(10), 0, viewPix(10));
        [_contentBtn addBorder:@"#EEEEEE" lineWidth:1 cornerRidus:3];
        _contentBtn.titleLabel.numberOfLines = 2;
        _contentBtn.userInteractionEnabled = NO;
        _contentBtn.cornerRidus = 3;
    }
    return _contentBtn;
}

-(UILabel *)leftLabel{
    if(!_leftLabel){
        _leftLabel = [UILabel lableWithText:@"" colorString:@"#606266" textFont:LGFontWeight(14, UIFontWeightMedium) textAlignment:NSTextAlignmentRight lines:1];
    }
    return _leftLabel;
}

-(UILabel *)rightLabel{
    if(!_rightLabel){
        _rightLabel = [UILabel lableWithText:@"天" colorString:@"#606266" textFont:LGFontWeight(14, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _rightLabel;
}

-(UITextField *)textField{
    if(!_textField){
        _textField = [[UITextField alloc]init];
        _textField.tintColor = [UIColor colorWithString:@"#5E8EF5"];
        _textField.textColor = [UIColor colorWithString:@"#606266"];
        _textField.textAlignment = NSTextAlignmentCenter;
        _textField.keyboardType = UIKeyboardTypeNumberPad;
        _textField.placeholder = @"";
        _textField.delegate = self;
        _textField.font = LGFontWeight(14, UIFontWeightMedium);
        [_textField addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _textField;
}

-(UIView *)lineView{
    if(!_lineView){
        _lineView = [[UIView alloc]init];
        _lineView.backgroundColor = [UIColor colorWithString:@"#606266"];
    }
    return _lineView;
}

@end



@interface LGCareMonitorHeaderView()

@end

@implementation LGCareMonitorHeaderView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.titleLabel];
    }
    return self;
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"" colorString:@"#282828" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(0, viewPix(10), Screen_W-viewPix(55), viewPix(23));
    }
    return _titleLabel;
}

@end
